package htime

import (
	if_expression "github.com/golang-infrastructure/go-if-expression"
	"strings"
	"time"
)

var (
	loc = time.Local
	// 1000-01-01 00:00:00至9999-12-31 23:59:59
	timeRegs = []StrToTime{}
)

type StrToTime interface {
	Check(s string) bool
	Result(strTime *StrTime) *time.Time
}

type StrTime struct {
	DateTime      string
	BaseTimestamp int64
	Loc           *time.Location
}

func Strtotime(s *StrTime) *time.Time {
	s.DateTime = strings.TrimSpace(s.DateTime)
	for _, m := range timeRegs {
		if m.Check(s.DateTime) {
			return m.Result(s)
		}
	}
	return nil
}

func SetLocation(l *time.Location) {
	loc = l
}

func getLoc(t *StrTime) *time.Location {
	return if_expression.Return(t.Loc == nil, loc, t.Loc)
}

func Register(toTime StrToTime) {
	timeRegs = append(timeRegs, toTime)
}

func filterSlices(strArr []string) []string {
	if len(strArr) == 0 {
		return nil
	}
	arr := make([]string, 0, len(strArr))
	for _, str := range strArr {
		if len(str) == 0 || str == " " {
			continue
		}
		arr = append(arr, str)
	}
	return arr
}
